import axios from 'axios'
import router from '../router'
import { ref } from 'vue'

// export const baseURL = 'http://localhost:3000'
export const baseURL = 'https://examapi.ywhdev.cn'
const instance = axios.create({
  baseURL: baseURL,
  timeout: 10000
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const t = localStorage.getItem('t')
    const uid = localStorage.getItem('uid')
    if (t) {
      config.headers.setAuthorization(`Bearer ${t}`)
    }
    if (uid) {
      config.headers.set('id-custom-header', uid)
    }

    return config
  },
  (err) => {
    Promise.reject(err)
  }
)
const isShow403 = ref()
const isShow401 = ref()
// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    return res
  },
  (err) => {
    if (err.message.split(' ')[0] === 'timeout') {
      return ElMessage.error('网络超时')
    }
    if (err?.response?.data.status === 401) {
      router.push('/login')
      localStorage.removeItem('uid')
      localStorage.removeItem('t')
      localStorage.removeItem('u')
      if (!isShow401.value) {
        isShow401.value = true
        ElMessage({
          message: err?.response?.data.message || '服务异常',
          type: 'error',
          onClose: () => {
            isShow401.value = false
          }
        })
      }
    }
    if (err.response.status === 403) {
      if (!isShow403.value) {
        isShow403.value = true
        ElMessageBox.alert('你已在别处登录，请重新登录', '登录提示', {
          showClose: false,
          callback: () => {
            router.push('/login')
            localStorage.removeItem('uid')
            localStorage.removeItem('t')
            localStorage.removeItem('u')
            isShow403.value = false
            console.log(isShow403.value)
          }
        })
      }
    }
    Promise.reject(err)
  }
)

export default instance
